package com.ym.manager.admin.upload;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ThumbnalitorUtil {

    private static final int kbMax = 1024;
    /**
     *
     * @Description:保存图片并且生成缩略图
     * @param imageFile 图片文件
     * @param request 请求对象
     * @param uploadPath 上传目录
     * @return
     */
    public static Map<String,Object> uploadFileAndCreateThumbnail(MultipartFile imageFile,HttpServletRequest request,String uploadPath) {
        Map<String, Object> map = new HashMap<String, Object>();
        if(imageFile == null ){
            map.put("code",-1);
            map.put("msg","图片不能为空");
            return map;
        }

        if (imageFile.getSize() >= 10*1024*1024) {
            map.put("code",-1);
            map.put("msg","图片不能超过10M");
            return map;
        }
        String uuid = UUID.randomUUID().toString();
        //拼接后台文件名称
        String pathName =  uuid + "."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //构建保存文件路劲
        //2016-5-6 yangkang 修改上传路径为服务器上
//        String realPath = request.getServletContext().getRealPath("uploadPath");
        //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置
        //String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
        //拼接文件路劲
        String filePathName = uploadPath + pathName;
        System.out.println("图片上传路径："+filePathName);
        //判断文件保存是否存在
        File file = new File(filePathName);
        if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
            //创建文件
            file.getParentFile().mkdirs();
        }

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            inputStream = imageFile.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            //写出文件
            //2016-05-12 yangkang 改为增加缓存
// IOUtils.copy(inputStream, fileOutputStream);
            byte[] buffer = new byte[2048];
            IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
            buffer = null;

        } catch (IOException e) {
            filePathName = null;
            map.put("code",-1);
            map.put("msg","系统异常");
            return map;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                filePathName = null;
            }
        }


//         String fileId = FastDFSClient.uploadFile(file, filePathName);

        /**
         * 缩略图begin
         */

        //拼接后台文件名称
        String thumbnailPathName = uuid + "-small."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //added by yangkang 2016-3-30 去掉后缀中包含的.png字符串
        if(thumbnailPathName.contains(".png")){
            thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
        }
        long size = imageFile.getSize();
        double scale = 1.0d ;
        if(size >= kbMax*1024){
            if(size > 0){
                scale = (512*1024f) / size ;
            }
        }


        //拼接文件路劲
        String thumbnailFilePathName = uploadPath + File.separator + thumbnailPathName;
        try {
            //added by chenshun 2016-3-22 注释掉之前长宽的方式，改用大小
// Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
            if(size < kbMax*1024){
                Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
            }else{
                Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
            }
            System.out.println(filePathName);
            System.out.println(thumbnailFilePathName);

        } catch (Exception e1) {
            map.put("code",-1);
            map.put("msg","系统异常");
            return map;
        }
        /**
         * 缩略图end
         */

        //原图地址
        map.put("originalUrl", pathName);
        //缩略图地址
        map.put("thumbnailUrl", thumbnailPathName);
        map.put("code",0);
        map.put("fileName",thumbnailPathName);
        map.put("data","https://www.ys168.vip/goods/promote/uploads/"+thumbnailPathName);
        return map;
    }

    public static void isDirectory(File file) throws IOException {
        int k = 1;
        if(file.exists()){
            if (file.isFile()) {

                File picture = new File(file.getAbsolutePath());
//                BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
//                System.out.println(String.format("%.1f",picture.length()/1024.0));
//                System.out.println(sourceImg.getWidth());
//                System.out.println(sourceImg.getHeight());

                long size = picture.length();
                double scale = 1.0d ;
                if(size >= kbMax*1024){
                    if(size > 0){
                        scale = (512*1024f) / size ;
                    }
                }
                String[] split = file.getAbsolutePath().split("\\\\");
                String thumbnailFilePathName = "small-"+split[split.length-1];

                Thumbnails.of(file.getAbsolutePath()).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(file.getAbsolutePath());
                /*  输出结果
                 * file is ==>>D:\qrcodeFile\20190116\5c594aee7a3d4b99b234b21456d053c4.png
                 * file is ==>>D:\qrcodeFile\20190116\95db451237344c51b4d797ddd9a71dce.png
                 * file is ==>>D:\qrcodeFile\20190117\5c594aee7a3d4b99b0c9b21456d053c4.png
                 * file is ==>>D:\qrcodeFile\20190117\95db457467344c51b4d797ddd9a71dce.png
                 * */
            }else{
                File[] list = file.listFiles();//list获取的结果：[D:\qrcodeFile\20190116, D:\qrcodeFile\20190117]
                if (list.length == 0) {
                    System.out.println(file.getAbsolutePath() + " is null");
                } else {
                    for (int i = 0; i < list.length; i++) {
                        isDirectory(list[i]);
                    }
                }
            }
        }else{
            System.out.println("文件不存在！");
        }
    }
    public static Map<String,Object> uploadFileApp(String appName,MultipartFile imageFile,HttpServletRequest request,String uploadPath) {
        Map<String, Object> map = new HashMap<String, Object>();
        if(imageFile == null ){
            map.put("code",-1);
            map.put("msg","app不能为空");
            return map;
        }

        //拼接后台文件名称
        String pathName =  appName + "."
                + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //构建保存文件路劲
        //2016-5-6 yangkang 修改上传路径为服务器上
//        String realPath = request.getServletContext().getRealPath("uploadPath");
        //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置
        //String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
        //拼接文件路劲
        String filePathName = uploadPath + pathName;
        System.out.println("app上传路径："+filePathName);
        //判断文件保存是否存在
        File file = new File(filePathName);
        if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
            //创建文件
            file.getParentFile().mkdirs();
        }

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            inputStream = imageFile.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            //写出文件
            //2016-05-12 yangkang 改为增加缓存
// IOUtils.copy(inputStream, fileOutputStream);
            byte[] buffer = new byte[2048];
            IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
            buffer = null;

        } catch (IOException e) {
            filePathName = null;
            map.put("code",-1);
            map.put("msg","系统异常");
            return map;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                filePathName = null;
            }
        }
        //原图地址
        //缩略图地址
        map.put("code",0);
        map.put("data",filePathName);
        return map;
    }
}
